package com.abc.cloud.common.utils;

import com.abc.cloud.common.enums.SysConfigEnums;
import com.abc.cloud.common.exception.MyException;
import com.abc.cloud.dto.sys.SystemSpace;
import com.abc.cloud.entity.SysConfigEntity;
import com.abc.cloud.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import static com.abc.cloud.common.constants.Constants.TOTAL_SPACE;
import static com.abc.cloud.common.constants.Constants.USE_SPACE;

@Component
public class SpaceUtil {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 更改系统内存
     * @param fileSize
     * @return
     */
    public Boolean changeSystemSpace(Long fileSize){
        SystemSpace systemSpace = this.getSystemSpace();

        if (systemSpace.getUseSpace() + fileSize > systemSpace.getTotalSpace()){
            redisTemplate.opsForValue().set(USE_SPACE, String.valueOf(systemSpace.getTotalSpace()));
            return false;
        }

        // 系统内存足够，增加使用内存
        Long finalUseSpace = systemSpace.getUseSpace() + fileSize;
        redisTemplate.opsForValue().set(USE_SPACE, String.valueOf(finalUseSpace > 0 ? finalUseSpace : 0));

        return true;
    }

    /**
     * 获取系统内存
     * @return
     */
    public SystemSpace getSystemSpace(){
        SystemSpace systemSpace = new SystemSpace();

        String useTotalStr = redisTemplate.opsForValue().get(USE_SPACE);
        String totalSpaceStr = redisTemplate.opsForValue().get(TOTAL_SPACE);

        if(useTotalStr == null){
            redisTemplate.opsForValue().set(USE_SPACE, String.valueOf(0L));
            systemSpace.setUseSpace(0L);
        }
        else{
            systemSpace.setUseSpace(Long.parseLong(useTotalStr));
        }

        if (totalSpaceStr == null){
            SysConfigEntity sysConfigEntity = sysConfigService.getById(SysConfigEnums.TOTAL_SPACE.getId());
            redisTemplate.opsForValue().set(TOTAL_SPACE, sysConfigEntity.getSysValue());
            systemSpace.setTotalSpace(Long.parseLong(sysConfigEntity.getSysValue()));
        }
        else {
            systemSpace.setTotalSpace(Long.parseLong(totalSpaceStr));
        }

        return systemSpace;
    }


}
